package com.lemon.boot.common.service.impl;

import com.lemon.boot.common.consts.RedisKeyConst;
import com.lemon.boot.common.entity.LoginUserDetail;
import com.lemon.boot.common.properties.JwtConfigProperties;
import com.lemon.boot.common.service.RedisService;
import com.lemon.boot.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 李猛
 * @datetime 2024/2/7 23:27
 * @description 类对象
 */
@Slf4j
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private IUserService iUserService;

    @Resource
    private RedisService redisService;

    @Resource
    private JwtConfigProperties properties;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据用户名获取用户信息
        LoginUserDetail result = iUserService.getByUsername(username);

        //2.获取资源集合
        List<String> resourceList = result.getAuthorities()
                .stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.toList());

        //3.把资源集合存入 redis
        String key = String.format("%s%s", RedisKeyConst.REDIS_KEY_LOGIN_USER, username);
        boolean save = redisService.save(key, resourceList, properties.getExpireTime(), TimeUnit.MINUTES);
        if (save) {
            return result;
        }
        log.error("redis保存用户资源失败");
        return null;
    }
}
